package cn.bigcontainer.alt.meta.service.impl;

import java.io.File;
import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import cn.bigcontainer.alt.common.util.BigConstant;
import cn.bigcontainer.alt.common.util.WoDateKit;
import cn.bigcontainer.alt.common.util.WoKit;
import cn.bigcontainer.alt.meta.dto.MFileDto;
import cn.bigcontainer.alt.meta.mapper.MFileMapper;
import cn.bigcontainer.alt.meta.po.MFile;
import cn.bigcontainer.alt.meta.service.MFileService;
import cn.bigcontainer.alt.meta.util.MUtil;
import lombok.SneakyThrows;

/**
 * @author jiaod
 * @date 2021年4月2日
 */
@Service
@Transactional
public class MFileServiceImpl implements MFileService {

	@Value("${big.upload.dir}")
    private String uploadDir;

    @Resource
    private MFileMapper fileMapper;
	
	@Override
	@SneakyThrows
	public MFileDto upload(MultipartFile multipartFile, Map<String, Object> req) {
		String name = multipartFile.getOriginalFilename();
        String uploadFile = uploadDir + "/" + getRelativePath(null, name);
        File file = WoKit.mkdirs(uploadFile);
        multipartFile.transferTo(file);
		return upload(null, name, req);
	}

	@Override
	public String getRelativePath(String module, String name) {
		if (WoKit.isEmpty(module)) {
			module = "upload";
		}
		return String.format("%s/%s/%d/%s", module, WoDateKit.getYearMonth(Calendar.getInstance()), Calendar.getInstance().get(Calendar.DAY_OF_MONTH), name);
	}
	
	public String getAbsolutePath(String module, String name) {
		return uploadDir + "/" + getRelativePath(module, name);
	}
	
	@Override
	@SneakyThrows
	public MFileDto upload(String module, String name, Map<String, Object> req) {
		String url = getRelativePath(module, name);
        String uploadFile = uploadDir + "/" + url;
        // 数据库中插入记录
        MFile mFile = new MFile();
        String type = uploadFile.substring(uploadFile.lastIndexOf('.') + 1);
        if (type.equals("")) {
            type = "file";
        }
        mFile.setType(type);
        mFile.setName(name);
        mFile.setUrl(url);
        // 设置当前用户
        mFile.setUserId(MUtil.getCurrentUserId(req));
        fileMapper.insert(mFile);
		return new MFileDto(mFile);
	}

	@Override
	public MFileDto getById(Integer id) {
		MFile mFile = fileMapper.selectById(id);
		if (mFile == null) {
			return null;
		}
		return new MFileDto(mFile);
	}

	@Override
	public File getFile(Integer id) {
		MFile mFile = fileMapper.selectById(id);
		String uploadFile = uploadDir + "/" + mFile.getUrl();
		return new File(uploadFile);
	}

	@Override
	public String getRootDir() {
		return uploadDir;
	}

}
